package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.mm.opensdk.utils.Log;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.YxInfo;
import com.ycsj.goldmedalnewconcept.bean.YxInfo.QUESTIONLISTBean;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.fragment.EmptyFragment;
import com.ycsj.goldmedalnewconcept.fragment.WordsYxFragment;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.supervp.SuperViewPager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//import com.iflytek.sunflower.FlowerCollector;

@SuppressLint("NewApi")
public class NewWordsYuXiActivity extends FragmentActivity implements
		OnClickListener, OnPageChangeListener {

	// 返回按钮
	private LinearLayout llBack;
	// 标题
	private TextView tvTitle;
	// 底部显示题目TextView
	private TextView tvPage;

	// 中间的ViewPager部分
	private SuperViewPager svp;

	// 外层的加载布局
	private LinearLayout llLoading;

	// 内容部分
	private LinearLayout llContent;

	// 单元的LessinId
	private int lESSON_ID;

	// 用于填充ViewPager的Fragment集合
	private List<Fragment> mFragments;

	// ViewPager的适配器对象
	private VpAdapter adpter;

	// 计时rid
	private String rid;
	
	// 页面返回的题目数据集合
	private List<QUESTIONLISTBean> questionlistBeans;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_words_yuxi);

		// 设置状态栏
		setBar();

		// 获取传递值
		initIntent();

		// 初始化视图
		initViews();

		// 设置监听
		initListener();

		// 请求服务器获取数据
		http();

		// 注册广播
		initRegisterBroadCast();

	}
	
	
	
	
	
	/**
	 * 获取传递过来的值
	 */
	private void initIntent() {
		lESSON_ID = getIntent().getExtras().getInt("lESSON_ID");
	}

	/**
	 * 初始化View的方法
	 */
	private void initViews() {
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		tvTitle = (TextView) findViewById(R.id.tv_title);
		svp = (SuperViewPager) findViewById(R.id.svp);
		tvPage = (TextView) findViewById(R.id.tv_page);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llContent = (LinearLayout) findViewById(R.id.ll_content);
		llLoading.setVisibility(View.VISIBLE);
		llContent.setVisibility(View.GONE);
	}

	/**
	 * 设置监听的方法
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		svp.setOnPageChangeListener(this);
	}

	/**
	 * 注册页面关闭和Vp跳转到第0页的广播
	 */
	private void initRegisterBroadCast() {
		IntentFilter firstfilter = new IntentFilter(
				"com.ycsj.goldmedalnewconcept.gotofirstpage");
		registerReceiver(new MyReceiver(), firstfilter);

		IntentFilter finishfilter = new IntentFilter(
				"com.ycsj.goldmedalnewconcept.newwordsyuxiactivityfinish");
		registerReceiver(new MyReceiver(), finishfilter);
		
		
		IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new TimingReceiver(), filter);
	}

	
	/**
	 * 断网计时广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class TimingReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			
			
			  // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
	        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
	            //获取联网状态的NetworkInfo对象
	            NetworkInfo info = intent
	                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
	            if (info != null) {
	                //如果当前的网络连接成功并且网络连接可用
	                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
	                    if (info.getType() == ConnectivityManager.TYPE_WIFI
	                            || info.getType() == ConnectivityManager.TYPE_MOBILE) {
	                    	
	                    	Log.i("test", "网络重新连接");
//	                    	UiHelper.toast(context, "网络重新连接");
	        				String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
//	        				HttpUtils httpUtils2 = new HttpUtils();
//	        				httpUtils2.configCurrentHttpCacheExpiry(1000);
//	        				httpUtils2.send(HttpMethod.GET,
//	        						NetConstant.USERONLINE
//	        								+ "InitInterfaceBegin.aspx?msg=1&type=3&account="
//	        								+ SPUtils.getString(NewWordsYuXiActivity.this, "account")
//	        								+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID,
//	        						callBackTime);
	                    }
	                }
	            }
	        }
			
//			if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())){
//			
//			}
		}
	}
	
	
	
	
	/**
	 * 广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if ("com.ycsj.goldmedalnewconcept.gotofirstpage".equals(intent
					.getAction())) {
				// 让ViewPager跳转到第0页
				svp.setCurrentItem(0);
			} else if ("com.ycsj.goldmedalnewconcept.newwordsyuxiactivityfinish"
					.equals(intent.getAction())) {
				// 关闭当前页面
				finish();
			}
		}
	}

	
	
	
	
	
	
	/**
	 * 请求服务器获取数据的方法
	 */
	private void http() {
		com.lidroid.xutils.HttpUtils httpUtils = new com.lidroid.xutils.HttpUtils();
		httpUtils.configCurrentHttpCacheExpiry(1000);
		httpUtils.send(
				HttpMethod.GET,
				NetConstant.TESTBANK
						+ "/GetLessonPrepareQuestion.aspx?lessonid="
						+ lESSON_ID
						+ "&account="
						+ SPUtils.getString(NewWordsYuXiActivity.this,
								ConfigConstant.USERNAME),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 请求成功
						String json = responseInfo.result;

						// 请求成功
						try {
							// 获取数据成功
							if (!TextUtils.isEmpty(json)) {
								YxInfo info = GsonUtil.jsonToBean(json,
										YxInfo.class);
								// 取出所有题目的集合
								questionlistBeans = info.QUESTION_LIST;
								if (questionlistBeans == null
										|| questionlistBeans.size() == 0) {
									// 证明当前没有题目信息
									runOnUiThread(new Runnable() {
										public void run() {

											if (null != llLoading) {
												llLoading
														.setVisibility(View.GONE);
											}

											UiHelper.toast(
													NewWordsYuXiActivity.this,
													"该单元无数据");
											return;
										}
									});

								} else {
									// 再次请求服务器获取点赞状态的数据
									setPageData();
								}

							}

						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// 请求失败
						runOnUiThread(new Runnable() {
							public void run() {
								if (null != llLoading) {
									llLoading.setVisibility(View.GONE);
									UiHelper.toast(NewWordsYuXiActivity.this,
											"网络错误");
								}
							}
						});
					}
				});
	}

	/**
	 * 设置页面数据的方法
	 */
	private void setPageData() {
		// 获取到题目数据,创建ViewPager的Framgent
		mFragments = new ArrayList<>();
		for (int i = 0; i < questionlistBeans.size(); i++) {
			mFragments.add(WordsYxFragment.newInstance(
					questionlistBeans.get(i), i, String.valueOf(lESSON_ID)));
		}
		// 添加最后一页的Fragment,就是一个空白的Framgent
		mFragments.add(new EmptyFragment());

		// 更新页面UI,给ViewPager设置适配器
		runOnUiThread(new Runnable() {
			public void run() {

				if (llLoading != null) {
					llLoading.setVisibility(View.GONE);
				}

				if (llContent != null) {
					llContent.setVisibility(View.VISIBLE);
				}

				// 第一步:设置底部的展示当前题目的TextView
				tvPage.setText("第1" + "/" + (questionlistBeans.size())
						+ "道题<---左滑下一题");
				// 第二步:设置顶部标题的文字
				tvTitle.setText(questionlistBeans.get(0).QUESTION_CONTENT);

				// 第三步:给Vp设置适配器

				adpter = new VpAdapter(getSupportFragmentManager());
				svp.setAdapter(adpter);
				
				svp.setOffscreenPageLimit(0);
			}
		});
	}

	/**
	 * 页面控件的点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_back:
			
			finish();
			break;

		default:
			break;
		}
	}

	/**
	 * ViewPager的滚动监听事件
	 * 
	 * @param pos
	 */
	@Override
	public void onPageScrollStateChanged(int pos) {

	}

	@Override
	public void onPageScrolled(int pos, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int pos) {
		// 如果不是最后一页则执行以下操作
		if (pos != mFragments.size() - 1) {
			// 第一步:同步标题栏的文字
			tvTitle.setText(questionlistBeans.get(pos).QUESTION_CONTENT);

			// 第二步:同步底部显示页面的文字
			tvPage.setText("第" + (pos + 1)  + "/"
					+ (questionlistBeans.size()) + "道题<---左滑下一题");

			// 第三步:发送同步状态的广告
			Intent intent = new Intent("com.ycsj.goldmedalnewconcept.sycstate");
			sendBroadcast(intent);
		}

	}

	/**
	 * ViewPager的适配器
	 */
	class VpAdapter extends FragmentStatePagerAdapter {

		public VpAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int pos) {
			return mFragments.get(pos);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

	}

	
	@Override
	protected void onResume() {
		super.onResume();

		String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET,
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=3&account="
						+ SPUtils.getString(this, "account")
						+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID,
				callBackTime);

	}
	
	/**
	 * 在生命周期中循环遍历删除录音文件
	 */
	@Override
	protected void onPause() {
		super.onPause();

		if(questionlistBeans!=null){

		for(int i=0;i<questionlistBeans.size();i++){
			File file = getFile(i);
			if(file.exists()){
				//文件存在则删除文件
				file.delete();
			}
		}
		}
		String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET, NetConstant.USERONLINE
				+ "SaveInterfaceEnd.aspx?msg=1&rid=" + rid + "&account="
				+ SPUtils.getString(this, "account"),
				callBackTimefinish);
	}
	
	
	private RequestCallBack<String> callBackTime = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			Log.i("test", json);
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;
//			UiHelper.toast(NewWordsYuXiActivity.this, "ID="+rid);
		}
 
		@Override
		public void onFailure(HttpException error, String msg) {
			rid = "";
		}
	};
	
	private RequestCallBack<String> callBackTimefinish = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
		}

		@Override
		public void onFailure(HttpException error, String msg) {

		}
	};
	
	
	
	/**
	 * 根据当前页面获取录音文件的方法
	 * 
	 * @return
	 */
	private File getFile(int postion) {
		File file = new File(
				getExternalCacheDir().getAbsolutePath()
				+ "/msc/"
				+ "icewordsyx"
				+ lESSON_ID
				+ postion
				+ ".wav");
		return file;
	}
	
	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
